package site.xuxingcan.util;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import site.xuxingcan.model.*;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * Created by xuxingcan on 2016/9/21.
 */
public class WeiXinUtil {
    public static Gson gson = new Gson();
    public static String XIAZHU_KEY = "开始下注";
    public static int XIAZHU_TIME = 1;
    public static String GONGGAO = "可自动加好友，自动抢包并下注！";
    //    public static int XIAZHU_START = 10;
//    public static int XIAZHU_END = 50;
    public static ArrayList<String> XIAZHU_LIST = new ArrayList<>();

    static {
        XIAZHU_LIST.add("20");
        XIAZHU_LIST.add("30");
        XIAZHU_LIST.add("40");
        XIAZHU_LIST.add("50");
    }

    public static String getUUID() {
        final String UUID = "window.QRLogin.uuid = ";
        String res = HttpUtil.sendGet("https://login.weixin.qq.com/jslogin?appid=wx782c26e4c19acffb&fun=new&lang=zh_CN&_=" + System.currentTimeMillis());
        if (res.contains(UUID)) {
            System.out.println(res);
            return res.substring(res.indexOf(UUID) + UUID.length() + 1, res.length() - 2);
        } else {
            return null;
        }
    }

    public static String waitForLogin() {
        String res = HttpUtil.sendGet("https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?tip=1&uuid=" + GlobalUtil.UUID + "&_=" + System.currentTimeMillis());
        if (null == res) {
            LogUtil.info("[*] 扫描二维码验证失败");
            return "";
        }
        String code = Matchers.match("window.code=(\\d+);", res);
        if (null == code) {
            LogUtil.info("[*] 扫描二维码验证失败");
            return "";
        } else {
            if (code.equals("201")) {
                LogUtil.info("[*] 成功扫描,请在手机上点击确认以登录");
            } else if (code.equals("200")) {
                LogUtil.info("[*] 正在登录...");
                String pm = Matchers.match("window.redirect_uri=\"(\\S+?)\";", res);

                String redirectHost = "wx.qq.com";
                try {
                    URL pmURL = new URL(pm);
                    redirectHost = pmURL.getHost();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                String pushServer = JSUtil.getPushServer(redirectHost);
                GlobalUtil.webpush_url = "https://" + pushServer + "/cgi-bin/mmwebwx-bin";

                GlobalUtil.redirect_uri = pm + "&fun=new";
                LogUtil.info("[*] redirect_uri=" + GlobalUtil.redirect_uri);
                GlobalUtil.base_uri = GlobalUtil.redirect_uri.substring(0, GlobalUtil.redirect_uri.lastIndexOf("/"));
                LogUtil.info("[*] base_uri=" + GlobalUtil.base_uri);
            } else if (code.equals("408")) {
                LogUtil.info("[*] 登录超时");
            } else {
                LogUtil.info("[*] 扫描code=" + code);
            }
        }
        return code;
    }

    public static void WXinit() {
        String url = GlobalUtil.base_uri + "/webwxinit?r=" + System.currentTimeMillis() + "&pass_ticket=" + GlobalUtil.pass_ticket + "&skey=" + GlobalUtil.skey;
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json;charset=utf-8");
        headers.put("Cookie", GlobalUtil.cookie);
        GlobalUtil.genBaseRequest();
        JsonObject jsonObject = new JsonObject();
        jsonObject.add("BaseRequest", gson.toJsonTree(GlobalUtil.mBaseRequest));
        String res = HttpUtil.sendPost(url, headers, jsonObject.toString());
        WXinitModel model = gson.fromJson(res, WXinitModel.class);
        GlobalUtil.SyncKey = model.getSyncKey();
        GlobalUtil.gen_synckey();
        GlobalUtil.userName = model.getUser().getUserName();
        GlobalUtil.nickName = model.getUser().getNickName();
        GlobalUtil.CharSet = model.getChatSet().split("[,]");
        LogUtil.info(res);
    }

    /**
     * 微信状态通知
     */
    public static boolean wxStatusNotify() {
        String url = GlobalUtil.base_uri + "/webwxstatusnotify?lang=zh_CN&pass_ticket=" + GlobalUtil.pass_ticket;
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json;charset=utf-8");
        headers.put("Cookie", GlobalUtil.cookie);
        JsonObject jsonObject = new JsonObject();
        jsonObject.add("BaseRequest", gson.toJsonTree(GlobalUtil.mBaseRequest));
        jsonObject.addProperty("Code", 3);
        jsonObject.addProperty("FromUserName", GlobalUtil.userName);
        jsonObject.addProperty("ToUserName", GlobalUtil.userName);
        jsonObject.addProperty("ClientMsgId", System.currentTimeMillis());
        String res = HttpUtil.sendPost(url, headers, jsonObject.toString());
        WXStatusNotifyModel model = gson.fromJson(res, WXStatusNotifyModel.class);
        return model.getBaseResponse().getRet() == 0;
    }

    /**
     * 获取联系人
     */
    public static boolean getContact() {
        String url = GlobalUtil.base_uri + "/webwxgetcontact?pass_ticket=" + GlobalUtil.pass_ticket + "&skey=" + GlobalUtil.skey + "&r=" + System.currentTimeMillis();
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json;charset=utf-8");
        headers.put("Cookie", GlobalUtil.cookie);
        JsonObject jsonObject = new JsonObject();
        jsonObject.add("BaseRequest", gson.toJsonTree(GlobalUtil.mBaseRequest));
        String res = HttpUtil.sendPost(url, headers, jsonObject.toString());
        WXContactModel model = gson.fromJson(res, WXContactModel.class);
        if (model.getBaseResponse().getRet() == 0) {
            for (WXContactModel.MemberListBean memberListBean : model.getMemberList()) {
                if (memberListBean.getUserName().startsWith("@@")) {
                    GlobalUtil.groupList.add(new GlobalUtil.Member(memberListBean.getUserName(), memberListBean.getNickName()));
                } else if (memberListBean.getUserName().startsWith("@") && memberListBean.getVerifyFlag() == 0) {
                    GlobalUtil.contactList.add(new GlobalUtil.Member(memberListBean.getUserName(), memberListBean.getNickName()));
                }
            }
        }
        int size = 0;
        JsonArray list = new JsonArray();
        for (String str : GlobalUtil.CharSet) {
            JsonObject user = new JsonObject();
            if (size >= 20) {
                getDetailContact(list);
                list = new JsonArray();
                size = 0;
            }
            if (str.startsWith("@@")) { //获取群明细
                user.addProperty("UserName", str);
                user.addProperty("EncryChatRoomId", "");
                size += 1;
                list.add(user);
            } else if (str.startsWith("@")) { //服务号
                user.addProperty("UserName", str);
                user.addProperty("ChatRoomId", "");
                size += 1;
                list.add(user);
            } else { //特殊帐号，不处理
            }
        }
        if (size > 0) {
            getDetailContact(list);
        }
        LogUtil.info(res);
        return false;
    }

    /**
     * 批处理获取联系人列表（主要是群联系人）
     *
     * @return
     */
    public static boolean getDetailContact(JsonArray list) {
        String url = GlobalUtil.base_uri + "/webwxbatchgetcontact?type=ex&pass_ticket=" + GlobalUtil.pass_ticket + "&r=" + System.currentTimeMillis();
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json;charset=utf-8");
        headers.put("Cookie", GlobalUtil.cookie);
        JsonObject jsonObject = new JsonObject();
        jsonObject.add("BaseRequest", gson.toJsonTree(GlobalUtil.mBaseRequest));
        jsonObject.addProperty("Count", list.size());
        jsonObject.add("List", list);
        String res = HttpUtil.sendPost(url, headers, jsonObject.toString());
        WXDetailContactModel model = gson.fromJson(res, WXDetailContactModel.class);
        if (model.getBaseResponse().getRet() == 0) {
            for (WXDetailContactModel.ContactListBean contactListBean : model.getContactList()) {
                if (contactListBean.getUserName().startsWith("@@")) {
                    GlobalUtil.groupList.add(new GlobalUtil.Member(contactListBean.getUserName(), contactListBean.getNickName()));
                }
            }
        }
        LogUtil.info(res);
        return false;
    }

    /**
     * 消息检查
     */
    public static int[] syncCheck() {
        int[] arr = new int[2];
        String url = GlobalUtil.webpush_url + "/synccheck?r=" + System.currentTimeMillis() / 10000 + getRandomString(4) + "&skey=" + GlobalUtil.skey + "&uin=" + GlobalUtil.wxuin + "&sid=" + GlobalUtil.wxsid + "&deviceid="
                + GlobalUtil.mBaseRequest.DeviceID + "&synckey=" + GlobalUtil.synckey + "&_=" + System.currentTimeMillis();
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Cookie", GlobalUtil.cookie);
        String res = HttpUtil.sendGet(url, headers);
        String retcode = Matchers.match("retcode:\"(\\d+)\",", res);
        String selector = Matchers.match("selector:\"(\\d+)\"}", res);
        if (null != retcode && null != selector) {
            arr[0] = Integer.parseInt(retcode);
            arr[1] = Integer.parseInt(selector);
            return arr;
        }
        return arr;
    }

    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static class SyncPar {
        public GlobalUtil.BaseRequest BaseRequest;
        public SyncKeyBean SyncKey;
        public String rr;
    }

    /**
     * 获取最新消息
     */
    public static String webwxsync() {
        String url = GlobalUtil.base_uri + "/webwxsync?lang=zh_CN&pass_ticket=" + GlobalUtil.pass_ticket
                + "&skey=" + GlobalUtil.skey + "&sid=" + GlobalUtil.wxsid + "&r=" + System.currentTimeMillis();
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json;charset=utf-8");
        headers.put("Cookie", GlobalUtil.cookie);
        SyncPar mPar = new SyncPar();
        mPar.BaseRequest = GlobalUtil.mBaseRequest;
        mPar.SyncKey = GlobalUtil.SyncKey;
        mPar.rr = System.currentTimeMillis() + "";
        String res = HttpUtil.sendPost(url, headers, gson.toJson(mPar));
        WXSyncModel model = gson.fromJson(res, WXSyncModel.class);
        if (model.getBaseResponse().getRet() == 0) {
            GlobalUtil.SyncKey = model.getSyncKey();
            GlobalUtil.gen_synckey();
        }
        LogUtil.info(res);
        return res;
    }

    public static class SendPar {
        public GlobalUtil.BaseRequest BaseRequest;
        public MsgBean Msg;

        public static class MsgBean {
            public int Type;
            public String Content;
            public String FromUserName;
            public String ToUserName;
            public String LocalID;
            public String ClientMsgId;
        }
    }

    /**
     * 发送文本消息
     *
     * @param content
     * @param to
     */
    public static String webwxsendmsg(String content, String to) {
        String url = GlobalUtil.base_uri + "/webwxsendmsg?lang=zh_CN&pass_ticket=" + GlobalUtil.pass_ticket;
        String clientMsgId = System.currentTimeMillis() / 10000 + getRandomString(4);
        SendPar par = new SendPar();
        par.BaseRequest = GlobalUtil.mBaseRequest;
        par.Msg = new SendPar.MsgBean();
        par.Msg.Type = 1;
        par.Msg.Content = content;
        par.Msg.FromUserName = GlobalUtil.userName;
        par.Msg.ToUserName = to;
        par.Msg.LocalID = clientMsgId;
        par.Msg.ClientMsgId = clientMsgId;
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json;charset=utf-8");
        headers.put("Cookie", GlobalUtil.cookie);
        String res = HttpUtil.sendPost(url, headers, gson.toJson(par));
        LogUtil.info(res);
        return res;
    }

    public static class AddUserModel {
        public GlobalUtil.BaseRequest BaseRequest;
        public int Opcode;
        public int VerifyUserListSize;
        public String VerifyContent;
        public int SceneListCount;
        public String skey;
        public List<VerifyUserListBean> VerifyUserList;
        public List<Integer> SceneList;

        public static class VerifyUserListBean {
            public String Value;
            public String VerifyUserTicket;

            public VerifyUserListBean(String value, String verifyUserTicket) {
                Value = value;
                VerifyUserTicket = verifyUserTicket;
            }
        }
    }

    public static void webAddUser(String value, String verifyUserTicket) {
        String url = GlobalUtil.base_uri + "/webwxverifyuser?r=" + System.currentTimeMillis();
        AddUserModel model = new AddUserModel();
        model.BaseRequest = GlobalUtil.mBaseRequest;
        model.Opcode = 3;
        model.VerifyUserList = new ArrayList<>();
        model.VerifyUserList.add(new AddUserModel.VerifyUserListBean(value, verifyUserTicket));
        model.VerifyUserListSize = 1;
        model.VerifyContent = "";
        model.SceneListCount = 1;
        model.SceneList = new ArrayList<>();
        model.SceneList.add(33);
        model.skey = GlobalUtil.skey;
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json;charset=utf-8");
        headers.put("Cookie", GlobalUtil.cookie);
        String res = HttpUtil.sendPost(url, headers, gson.toJson(model));
        LogUtil.info(res);
    }
}
